package com.shanghaionstar.user;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.common.util.Constants;
import com.onstar.cn.framework.annotation.FindViewById;
import com.onstar.cn.framework.annotation.OnClick;
import com.onstar.cn.framework.mvp.base.core.BaseFragment;
import com.onstar.cn.more.entity.SubscriberDTO;
import com.onstar.cn.more.response.PrepaidCardResponse;
import com.onstar.cn.vehicle.entity.ErrorEnum;
import com.onstar.cn.vehicle.entity.ErrorInfo;
import com.onstar.cn.weight.CustomImageView;
import com.shanghaionstar.OnstarApplication;
import com.shanghaionstar.R;
import com.shanghaionstar.enumtype.ActivateType;
import com.shanghaionstar.enumtype.FunctionNameFindId;
import com.shanghaionstar.user.iview.IPayCardDetailView;
import com.shanghaionstar.user.presenter.PayCardDetailPresenter;
import com.shanghaionstar.utils.AlertDialogUtil;
import com.shanghaionstar.utils.ApplicationUtil;
import com.shanghaionstar.utils.BusinessUtil;
import com.shanghaionstar.utils.ErrorCodeUtil;
import com.shanghaionstar.utils.FinalConstants;
import com.shanghaionstar.utils.JoinMeConstants;
import com.shanghaionstar.weight.TopLayout;

import java.io.Serializable;
import java.util.Locale;

/**
 * Created by Mengzhou Gu on 2016/8/2.
 */
public class PayCardDetailFragment extends BaseFragment implements IPayCardDetailView, View.OnClickListener {
    @FindViewById
    LinearLayout owner_ppcd_date_value_core, owner_ppcd_date_value_data;
    @FindViewById
    private CircleImageView head_iv;
    private PrePayActivity  parentActivity;
    @FindViewById
    private TextView tv_car_brank    = null;// 车的品牌
    @FindViewById
    private TextView tv_vin_number   = null;// 车架号
    @FindViewById
    private TextView tv_name         = null;// 车主姓名
    @FindViewById
    private TextView tv_phone_number = null;// 车主电话号码

    @FindViewById
    private TextView tv_package_name_value = null;
    @FindViewById
    private TextView tv_end_date_value     = null;//核心卡显示开始结束时间
    @FindViewById
    private TextView tv_date_value         = null;//流量卡卡有效期yqt

    @FindViewById
    private Button    btn_ppcd_activite = null;// 激活按钮
    @FindViewById
    private TopLayout top_layout        = null;
    private ProgressDialog mDialog;
    private Bundle        bundle     = null;
    private SubscriberDTO accout_obj = null;
    private String        vin        = null;
    private PrepaidCardResponse activateCardResponse;
    @FindViewById
    private TextView            tv_start_date_value;
    @FindViewById
    private TextView            tv_description;
    private String              card_number;
    private String              card_password;
    @FindViewById(background = R.drawable.onstar_join_me_bg)
    private RelativeLayout      layout_background;

    @FindViewById(background = R.drawable.user_cardpay_head)
    private CustomImageView iv_user_icon;

    @FindViewById(background = R.drawable.user_paycard_line_one)
    private CustomImageView iv_line;

    @FindViewById(background = R.drawable.user_ppc_detail_line_second)
    private CustomImageView detail_line, img_line;

    @FindViewById(background = R.drawable.user_payme_bottom_line)
    private CustomImageView        end_line;
    private ProgressDialog         dialog;
    private String                 model;
    private String                 make;
    private OnstarApplication      myApp;
    private Serializable           activeType;
    private PayCardDetailPresenter presenter;

    @Override
    public int getLayoutId() {
        return R.layout.user_paycarddetail_fragment;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        parentActivity = (PrePayActivity) activity;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        myApp = (OnstarApplication) getActivity().getApplicationContext();
        bundle = getArguments();
     // String imageUrl = ShareUtils.getString("imageUrl", parentActivity);
        String imageUrl="";
        if(myApp.getHeadImgRes()!=null) {
            imageUrl = myApp.getHeadImgRes().getFullUrl();
        }
        if (bundle == null) {
            return;
        }
        presenter = new PayCardDetailPresenter(parentActivity.getScheduler(), bundle);
        presenter.setView(this);
        if (isFirstLoad()) {
            parentActivity.current_fragment = "PayCardDetailFragment";

            accout_obj = (SubscriberDTO) bundle.getSerializable("account_obj");
            activateCardResponse = (PrepaidCardResponse) bundle.getSerializable("obj");
            vin = bundle.getString("vin");
            card_number = bundle.getString("card_number");
            card_password = bundle.getString("card_password");
            model = bundle.getString("model");
            make = bundle.getString("make");
            activeType = bundle.getSerializable("activateType");
            initView(activeType,imageUrl);
            if (accout_obj == null) {
                accout_obj = new SubscriberDTO();
                // accout_obj.setAccountId(activateCardResponse.getAccountInfo().getAccountID());
                // subscriber.setModel(model);
                // subscriber.setModel(vin);
                if (activateCardResponse.getAccountInfo() != null) {
                    accout_obj.setFirstName(activateCardResponse.getAccountInfo().getFirstName());
                    accout_obj.setLastName(activateCardResponse.getAccountInfo().getLastName());
                    accout_obj.setPhoneNumber(activateCardResponse.getAccountInfo().getPhoneNumber());
                }
            }
            setAccountValue(accout_obj, activateCardResponse);
            top_layout.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    BusinessUtil.sendReportByClickType(getActivity(), FunctionNameFindId.Prepaidcardactive_activecancel.getStringValue());
                    back();
                }
            });
        }
    }

    private void setAccountValue(SubscriberDTO accout_obj, @NonNull  PrepaidCardResponse activateCardResponse) {
        if (!CommonUtil.isNull(accout_obj)) {
            if (!CommonUtil.isNull(accout_obj.getMake()) && !CommonUtil.isNull(accout_obj.getModel())) {
                tv_car_brank.setText(accout_obj.getMake() + accout_obj.getModel());
            } else {
                tv_car_brank.setText(make + model);
            }
            if (!vin.equals("") && vin != null) {
                tv_vin_number.setText(CommonUtil.maskWithStar(vin, 3, 4));
            }
            if (!"".equals(accout_obj.getLastName()) && accout_obj.getLastName() != null) {
                tv_name.setText(accout_obj.getLastName() + " " + getString(R.string.xx));
            }

            if (accout_obj.getPhoneNumber() != null || activateCardResponse.getAccountInfo().getPhoneNumber() != null) {
                if (accout_obj.getPhoneNumber() != null) {
                    String phoneNum = CommonUtil.replaceString(accout_obj.getPhoneNumber(), false);
                    tv_phone_number.setText(CommonUtil.maskWithStar(phoneNum, 3, 4));
                } else {
                    String phoneNum = CommonUtil.replaceString(activateCardResponse.getAccountInfo().getPhoneNumber(), false);
                    tv_phone_number.setText(CommonUtil.maskWithStar(phoneNum, 3, 4));
                }
            } else {
                if (accout_obj.getEmail() != null || activateCardResponse.getAccountInfo().getEmail() != null) {
                    if (accout_obj.getEmail() != null) {
                        String email = CommonUtil.replaceEmail(activateCardResponse.getAccountInfo().getEmail(), true);
                        tv_phone_number.setText(CommonUtil.maskWithStar(email, 3, 4));
                    } else {
                        String email = CommonUtil.replaceEmail(activateCardResponse.getAccountInfo().getEmail(), true);
                        tv_phone_number.setText(CommonUtil.maskWithStar(email, 3, 4));
                    }
                }
            }


            if (activateCardResponse != null && activateCardResponse.getPackageInfo() != null && activateCardResponse.getPackageInfo().getPackageType().equalsIgnoreCase("CORE")) {
                owner_ppcd_date_value_data.setVisibility(View.GONE);
                owner_ppcd_date_value_core.setVisibility(View.VISIBLE);
                if (!CommonUtil.isNull(activateCardResponse.getPackageInfo().getPackageName())) {
                    tv_package_name_value.setText(activateCardResponse.getPackageInfo().getPackageName());
                }
                if (activateCardResponse.getPackageInfo().getPackageType().equalsIgnoreCase("data")) {
                    tv_end_date_value.setText(activateCardResponse.getPackageInfo().getDuration() + getString(R.string.ppc_day));
                } else {
                    // 开始日期
                    if (!CommonUtil.isNull(activateCardResponse.getPackageInfo().getStartDate())) {
                        tv_start_date_value.setText(activateCardResponse.getPackageInfo().getStartDate().subSequence(0, 10));
                    }
                    // 结束日期

                    if (!CommonUtil.isNull(activateCardResponse.getPackageInfo().getEndDate())) {
                        tv_end_date_value.setText(activateCardResponse.getPackageInfo().getEndDate().substring(0, 10));
                    }

                }
                if (!CommonUtil.isNull(activateCardResponse.getPackageInfo().getDescription())) {
                    tv_description.setText(activateCardResponse.getPackageInfo().getDescription());
                }
            } else {
                owner_ppcd_date_value_core.setVisibility(View.GONE);
                owner_ppcd_date_value_data.setVisibility(View.VISIBLE);
                if (!CommonUtil.isNull(activateCardResponse.getPackageInfo().getPackageName())) {
                    tv_package_name_value.setText(activateCardResponse.getPackageInfo().getPackageName());
                }
                if (activateCardResponse.getPackageInfo().getPackageType().equalsIgnoreCase("data")) {
                    tv_end_date_value.setText(activateCardResponse.getPackageInfo().getDuration() + getString(R.string.ppc_day));
                } else {
                    // 开始日期
                    if (!CommonUtil.isNull(activateCardResponse.getPackageInfo().getStartDate())) {
                        tv_start_date_value.setText(activateCardResponse.getPackageInfo().getStartDate().subSequence(0, 10));
                    }
                    // 结束日期

                    if (!CommonUtil.isNull(activateCardResponse.getPackageInfo().getEndDate())) {
                        tv_end_date_value.setText(activateCardResponse.getPackageInfo().getEndDate().substring(0, 10));
                    }

                }
                if (!CommonUtil.isNull(activateCardResponse.getPackageInfo().getDescription())) {
                    tv_description.setText(activateCardResponse.getPackageInfo().getDescription());
                }
            }
        }
    }


    /*    private void initView(Serializable activeType) {
            if (activeType.equals(ActivateType.Subscriber)) {
                DisplayImageOptions options = OnstarApplication.getOptions(false, R.drawable.def_login_head);
                if (myApp.getHeadImgRes() != null) {
                    ImageLoader.getInstance().displayImage(myApp.getHeadImgRes().getFullUrl(), head_iv, options);
                }
            } else {
                *//*为他人激活显示默认头像*//*
        }
    }*/
    private void initView(Serializable activeType,String url) {
        if (activeType.equals(ActivateType.Subscriber)) {
            DisplayImageOptions options = OnstarApplication.getOptions(false, R.drawable.def_login_head);
            if (url != null) {
                ImageLoader.getInstance().displayImage(url, head_iv, options);
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        top_layout = null;
    }

    @Override
    public void setLoading(boolean isLoading) {
        if (isLoading) {
            dialog = showLoadProgress();
            dialog.show();
        } else {
            dismissDialog(dialog);
        }
    }

    @OnClick(R.id.btn_ppcd_activate)
    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_ppcd_activate) {
            BusinessUtil.sendReportByClickType(getActivity(), FunctionNameFindId.Prepaidcardactive_comfirm.getStringValue());
            // activatePrepaidCard();
            presenter.getData();
        }
    }

    @Override
    public void onResponseError(OnStarException e) {

    }

    @Override
    public void onReponseSuccess(PrepaidCardResponse object) {

    }

    @Override
    public Activity onActivity() {
        return getActivity();
    }


    @Override
    public void showSuccess(PrepaidCardResponse prepaidCardResponse) {
        dismissDialog(dialog);
        // 进行判断是否成功激活
        if (prepaidCardResponse.getStatus().equals("SUCCESS")) {
            showDialog();
        }
    }

    @Override
    public void showFailure() {
        ErrorInfo errorInfo2 = new ErrorInfo();
        errorInfo2.setCode(ErrorEnum.SB027_MSG002.getStringValue());
        ErrorCodeUtil.ShowErrorSompMsg(getActivity(), errorInfo2);
    }


    @Override
    public void showError(Bundle bundle, Throwable throwable) {
        ErrorInfo errorInfo = (ErrorInfo) bundle.getSerializable("errorInfo");

        ErrorCodeUtil.ShowErrorSompMsg(getActivity(), errorInfo);
    }

    public void changeFragment(FragmentManager fragmentManager, Fragment fragment, String tag) {
        if (null != fragmentManager.findFragmentByTag(tag))
            return;
        FragmentTransaction p_FragmentTransaction = fragmentManager.beginTransaction();
        p_FragmentTransaction.replace(R.id.fragment_container, fragment, tag);
        p_FragmentTransaction.addToBackStack(null);
        p_FragmentTransaction.commitAllowingStateLoss();
    }


    @Override
    public void onResume() {
        super.onResume();
        if (PayCardFragment.backFromActiveHis) {
            new Handler().post(new Runnable() {
                @Override
                public void run() {
                    back();
                }
            });
        }
    }

    private void showDialog() {
        AlertDialogUtil.showAlertDialog(parentActivity, R.string.dialog_warning, R.string.activite_sucess,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
//                        BusinessUtil.sendReportByClickType(getActivity(),
//                                FunctionNameFindId.PPC_activate_button.getStringValue());
                        BusinessUtil.updateConfigValue("Owner_jump", "false", parentActivity);
                        String loginRole = ApplicationUtil.getInstance().getLoginRole();

                        if (bundle != null && bundle.containsKey(FinalConstants.PREPAID_CARD_ACTIVATE_TYPE)) {
                            String activateType = bundle.getString(FinalConstants.PREPAID_CARD_ACTIVATE_TYPE);
                            if (!CommonUtil.isNull(activateType) && activateType.equalsIgnoreCase(ActivateType.Other.name())) {
                                /*不跳visitor详情页 yqt*/
                                /*if (activateCardResponse != null && accout_obj != null) {
                                    bundle.putSerializable("active_obj", activateCardResponse);
									bundle.putSerializable("accout_obj", accout_obj);
									bundle.putString("vin", vin);
									bundle.putString("makeModel", tv_car_brank.getText().toString());
									bundle.putString("card_number", card_number);
									parent.setCurrentFragment("VisitorDetailfragment");
									VisitorDetailfragment visitorfragment = new VisitorDetailfragment();
									visitorfragment.setArguments(bundle);
									changeFragment(parent.fragmentManager, visitorfragment,
											VisitorDetailfragment.class.getName());
								}*/
                                return;
                            }
                        }

                        if (!CommonUtil.isNull(loginRole) && !loginRole.equalsIgnoreCase(JoinMeConstants.VISITOR)) {
                            if (ApplicationUtil.getInstance().getLoginRole().toLowerCase(Locale.CHINA).equals(Constants.OWNER)
                                    || ApplicationUtil.getInstance().getLoginRole().toLowerCase(Locale.CHINA).equals(Constants.PROXY)
                                    || ApplicationUtil.getInstance().getLoginRole().toLowerCase(Locale.CHINA).equals(Constants.DRIVER)) {
                                bundle.putSerializable("vin", vin);
                                bundle.putString("from", PayCardDetailFragment.class.getSimpleName());
                                ActiviteHistoryFragment activiteHistoryfragment = new ActiviteHistoryFragment();
                                activiteHistoryfragment.setArguments(bundle);
                                parentActivity.changeFragment(parentActivity.fragmentManager, activiteHistoryfragment,
                                        ActiviteHistoryFragment.class, true);
                                return;
                            }
                        }
						/*不跳visitor详情页 yqt*/
						/*if (activateCardResponse != null && accout_obj != null) {
							bundle.putSerializable("active_obj", activateCardResponse);
							bundle.putSerializable("accout_obj", accout_obj);
							bundle.putString("vin", vin);
							bundle.putString("makeModel", tv_car_brank.getText().toString());
							bundle.putString("card_number", card_number);
							parent.setCurrentFragment("VisitorDetailfragment");
							VisitorDetailfragment visitorfragment = new VisitorDetailfragment();
							visitorfragment.setArguments(bundle);
							changeFragment(parent.fragmentManager, visitorfragment,
									VisitorDetailfragment.class.getName()); //不跳详情页
						}*/
                    }
                });
    }

    @Override
    public void onFragmentBackPress() {
//        super.onFragmentBackPress();
//        back();
        parentActivity.getSupportFragmentManager().popBackStack();

        BusinessUtil.sendReportByClickType(getActivity(), FunctionNameFindId.Prepaidcardactive_activecancel.getStringValue());

    }
}
